﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using RTW.DAL;
using RTW.OA.Models;
using RTW.Utils.Common;
using RTW.Utils.Utils;

namespace RTW.OA.Servers
{
    public static class CommServers
    {
        private static readonly IRepository<sys_cfg> CommRepository = new DapperRepository<sys_cfg>();


        public static List<sys_cfg> GetSysCfg()
        {
            List<sys_cfg> model = CacheUtil.Get<List<sys_cfg>>("CACHE_SYS_CONFIG");
            if (model==null|| model.Count==0)
            {
                CacheUtil.Insert("CACHE_SYS_CONFIG", CommRepository.GetAllEnumerable().ToList());
                    //Utils.GetXmlMapPath(DTKeys.FILE_SYS_XML_CONFING));
                model = CacheUtil.Get<List<sys_cfg>>("CACHE_SYS_CONFIG");
            }
            return model;
        }

        public static sysconfig LoadSysConfig()
        {
            sysconfig model = CacheHelper.Get<sysconfig>(DTKeys.CACHE_SYS_CONFIG);
            if (model == null)
            {
                CacheHelper.Insert(DTKeys.CACHE_SYS_CONFIG,(sysconfig)SerializationHelper.Load(typeof(sysconfig), RTW.Utils.Common.Utils.GetXmlMapPath(DTKeys.FILE_SYS_XML_CONFING)),
                    RTW.Utils.Common.Utils.GetXmlMapPath(DTKeys.FILE_SYS_XML_CONFING));
                model = CacheHelper.Get<sysconfig>(DTKeys.CACHE_SYS_CONFIG);
            }
            return model;
        }


        /// <summary>
        ///  保存配置文件
        /// </summary>
        public static sysconfig SaveSysConifg(sysconfig model)
        {
            SerializationHelper.Save(model, Utils.Common.Utils.GetXmlMapPath(DTKeys.FILE_SYS_XML_CONFING));
            return model;
        }

        //权限
        public static List<actionpermission> GetPermissions(string userid)
        {
            var permissions = CommRepository.SqlWithParamsDynamic(@"SELECT
                                    *
                                FROM

                                    actionpermission
                                WHERE
                                charindex(',' + ltrim(PERMISSION_ID) + ',', (SELECT

                                    FUNC_ID_STR
                                FROM

                                    role
                                WHERE

                                    ROLE_ID IN(SELECT USER_PRIV FROM users WHERE USER_ID = @USERID))) > 0", new { USERID = userid });
            return AutoMapper.Mapper.Map<List<actionpermission>>(permissions);
        }


        public static string GetDataRight(string userid)
        {
            return "";

        }
    }
}